package com.northpool.operator.common.algorithm;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.northpool.operator.IOperatorHandler;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.ParamUtils;
import com.northpool.operator.utils.ServeOperatorHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class OperatorTestBuild {
    private static final Logger log = LoggerFactory.getLogger(OperatorTestBuild.class);

    public static void execute(Class<? extends IOperatorHandler> cla, Map<String, String> params) {
        InputParams inputParams = AnnotationUtil.getAnnotation(cla.getConstructors()[0], InputParams.class);

        ParamTool.Builder builder = ParamTool.aBuilder();
        InputParam[] inputParamsArr = inputParams == null ? new InputParam[0] : inputParams.value();
        for (InputParam inputParam : inputParamsArr) {
            String ref = inputParam.ref();
            String value = inputParam.value();
            if (!params.containsKey(ref)) {
                builder.add(inputParam, StrUtil.isEmpty(value) ? "" : value);
            } else {
                String paramVal = ParamUtils.parseValue(params.get(ref));
                builder.add(inputParam, paramVal);
            }
        }
        ParamTool paramTool = builder.build();
        IOperatorHandler iOperatorHandler;
        if (ServeOperatorHelper.class.isAssignableFrom(cla)) {
            iOperatorHandler = ReflectUtil.newInstance(cla, paramTool);
        } else {
            iOperatorHandler = ReflectUtil.newInstance(cla);
        }

        try {
            iOperatorHandler.execute(paramTool);
            System.exit(0);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("算子执行异常");
        }
    }

}
